package com.banksoft.cps.util;

import org.apache.log4j.Logger;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @version 1.0
 */
public class ConfigHelper {
    private Logger logger = Logger.getLogger(ConfigHelper.class);

    private static ConfigHelper helper;

    private static Properties configProperties;

    private ConfigHelper() {
        loadConfig();
    }

    private void loadConfig() {
        logger.info("load config.properties");
        configProperties = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = ConfigHelper.class.getResourceAsStream("/config.properties");
            configProperties.load(inputStream);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static ConfigHelper getInstance() {
        if (helper == null) {
            helper = new ConfigHelper();
        }
        return helper;
    }

    public String getConfig(String key) {
        try {
            return (String) configProperties.get(key);
        } catch (Exception ex) {
            logger.error("load config.properties error,key is:"+key,ex);
            loadConfig();
            return (String) configProperties.get(key);
        }
    }

    public int getInteger(String key) {
        return Integer.parseInt(getConfig(key));
    }
    public void setProperties(String key , String value){
        try {
            String path = ConfigHelper.class.getClassLoader().getResource("/config.properties").toURI().getPath();
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            configProperties.put(key, value);
            configProperties.store(fileOutputStream,"activity set for special army");
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}